/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 
package com.youngfey.wordmaster.database.tables

import com.youngfey.database.annotation.*
import com.youngfey.wordmaster.database.*
import static com.youngfey.wordmaster.database.Database.*

@Unique(['WORD, SENTENCE, OFFSET'])
public class WordIndex {
    Word word
    Sentence sentence
    Integer offset

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    Integer id
    

    boolean equals(Object o) {
        id != null && o instanceof WordIndex && id == o.getId()
    }

    static createTable() {
        execute("CREATE TABLE WordIndex (Id INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT WORDINDEX_PK PRIMARY KEY, Word INT NOT NULL, Sentence INT NOT NULL, Offset INT NOT NULL)")
        
        execute('CREATE UNIQUE INDEX UIX_WORD_SENTENCE_OFFSET__WORDINDEX ON WordIndex (WORD, SENTENCE, OFFSET)')
        
    }

    boolean isValid() {
        word != null && sentence != null && offset != null
    }


    boolean isConflicted() {
    
        def idUIX_WORD_SENTENCE_OFFSET = findIdByUIX_WORD_SENTENCE_OFFSET(wORD, sENTENCE, oFFSET)
        if(idUIX_WORD_SENTENCE_OFFSET != null && idUIX_WORD_SENTENCE_OFFSET != id) return true
    
        false
    }

    
    Integer findIdByUIX_WORD_SENTENCE_OFFSET(wORD, sENTENCE, oFFSET) {
        firstRow("SELECT ID FROM WordIndex WHERE WORD = $wORD AND SENTENCE = $sENTENCE AND OFFSET = $oFFSET")?.id
    }
    


    static WordIndex create(word, sentence, offset) {
        def instance = new WordIndex(word: word, sentence: sentence, offset: offset)
        instance.insert()
        instance
    }

    def insert() {
        if(id == null && isValid()) {
            id = executeInsert("INSERT INTO WordIndex (Word, Sentence, Offset) VALUES (${word?.getId()}, ${sentence?.getId()}, ${offset})")[0][0]
            if(id != null) {
                
                return
            }
        }

        throw new IllegalStateException()
    }

    //capitalize;
    static WordIndex find(Integer id) {
        if(id == null) return null

        

        def row = firstRow("SELECT * FROM WordIndex WHERE Id = $id")
        
        row ? new WordIndex(id: row.Id, word: Word.find((Short)row.word), sentence: Sentence.find((Short)row.sentence), offset: row.offset) : null
        
    }

    static ArrayList<WordIndex> findBySql(stmt) {
        def rows = []
        eachRow(stmt) {row ->
            rows << new WordIndex(id: row.Id, word: Word.find((Short)row.word), sentence: Sentence.find((Short)row.sentence), offset: row.offset)
        }
        
        rows
    }

    static ArrayList<WordIndex> findAll() {
        findBySql('SELECT * FROM WordIndex')
    }

    

    private executeUpdate(stmt) {
        def updated = executeUpdate(stmt)
        if(updated != 1) throw new IllegalStateException()
        
    }

    def update() {
        if(id != null && isValid()) {
            executeUpdate("UPDATE WordIndex SET Word = ${word?.getId()}, Sentence = ${sentence?.getId()}, Offset = ${offset} WHERE Id = $id")
        }
    }

    static delete(Integer id) {
        execute("DELETE FROM WordIndex WHERE Id = $id")
        
    }

    def delete() {
        if(id != null) delete(id)
    }


    static ArrayList<WordIndex> findByWord(value) {
        findBySql("SELECT * FROM WordIndex WHERE Word = ${value?.getId()}")
    }

    static ArrayList<WordIndex> findBySentence(value) {
        findBySql("SELECT * FROM WordIndex WHERE Sentence = ${value?.getId()}")
    }

    static ArrayList<WordIndex> findByOffset(value) {
        findBySql("SELECT * FROM WordIndex WHERE Offset = ${value}")
    }



    static ArrayList<WordIndex> findByWordLike(String keyword) {
        findBySql("SELECT * FROM WordIndex WHERE Word LIKE $keyword")
    }

    static ArrayList<WordIndex> findBySentenceLike(String keyword) {
        findBySql("SELECT * FROM WordIndex WHERE Sentence LIKE $keyword")
    }

    static ArrayList<WordIndex> findByOffsetLike(String keyword) {
        findBySql("SELECT * FROM WordIndex WHERE Offset LIKE $keyword")
    }



    def updateWord(value) {
        this.word = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE WordIndex SET Word = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateSentence(value) {
        this.sentence = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE WordIndex SET Sentence = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateOffset(value) {
        this.offset = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE WordIndex SET Offset = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }



    // </editor-fold>
}
